﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using SalesSys.Comm.DAL;

namespace SalesSys.DAL.Base
{
    /// <summary>
    /// 普通实体基类
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    public abstract class DbEntityBase<TKey> : IDbEntity<TKey>
    {
        public DbEntityBase()
        {
            if (Id is Guid)
            {
                var thisEn= this as DbEntityBase<Guid>;
                thisEn.Id = BaseTypeEx.NewTimeGuid();// Guid.NewGuid();
                
            }
        }
        [Key]
        public virtual TKey Id { get; set; }

     

        #region IDbEntity 成员

      public   object[] GetKeyValues()
        {
            return new object[] { Id };
        }

        public void SetKeyValues(object[] keyValues)
        {
            Id = (TKey)keyValues[0];
        }

        #endregion
    }
   
    public abstract class TimestampEntity<T> : DbEntityBase<T>, ITimestampEntity
    {
        /// <summary>
        /// 并发版本控制
        /// </summary>
        [Timestamp]
        public byte[] RowVersion { get; set; }
    }
     
    /// <summary>
    /// 树形基类
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TTreeEntity"></typeparam>
    public abstract class TreeEntity<TKey, TTreeEntity> : DbEntityBase<TKey>, ITreeEntity<TKey, TTreeEntity>
        where TTreeEntity : ITreeEntity
        where TKey : struct
    {
        public TreeEntity()
        {
            Children = new HashSet<TTreeEntity>();
        }
        ITreeEntity ITreeEntity.Parent
        {
            get { return Parent; }
            set { Parent = (TTreeEntity)value; }
        }

        IEnumerable<ITreeEntity> ITreeEntity.Children
        {
            get { return Children.Cast<ITreeEntity>(); }
            set { Children =  value.Cast<TTreeEntity>().ToList(); }
        }

        
        object ITreeEntity.ParentId
        {
            get { return ParentId; }
            set { ParentId = (TKey)value; }
        }

        public virtual ICollection<TTreeEntity> Children { get; set; }

        public virtual TKey? ParentId { get; set; }

        public virtual TTreeEntity Parent { get; set; }
    }
}
